/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useCallback, useImperativeHandle, forwardRef } from 'react';
import { useDispatch, useSelector } from 'dva';
import { Tree, Spin, Affix, Row, Col, Icon } from 'antd';
import { debounce, isEmpty, cloneDeep } from 'lodash';
import { isLegalData } from '@/utils/utils';
import styles from './index.less';
import { ZyAdd } from '../ZY_add_roles';

const { DirectoryTree, TreeNode } = Tree;

// 后去父级节点
const getParent = (parentNode, selectKey) => {
  let arrRes = [];
  if (parentNode.length == 0) {
    if (selectKey) {
      arrRes.unshift(parentNode);
    }
    return arrRes;
  }
  const rev = (data, nodeId) => {
    for (let i = 0, { length } = data; i < length; i += 1) {
      const node = data[i];
      if (node.id == nodeId) {
        arrRes.unshift(node);
        rev(parentNode, node.pid);
        break;
      } else if (node.children) {
        rev(node.children, nodeId);
      }
    }
    return arrRes;
  };
  arrRes = rev(parentNode, selectKey);
  return arrRes;
};

const titleMap = {
  post: '添加支局',
  yjy: '添加县级网点',
};

const AddressTree = forwardRef((props, ref) => {
  const { userInfo, isInfoReady } = props;
  const { branchId: companyId, branchName, branchLevel } = userInfo;
  const { key } = useSelector(({ setting }) => setting.options);
  const dispatch = useDispatch();
  const [treeList, setTreeData] = useState([]);
  const [selectKey, setSelectKey] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedItem, setSelectedItem] = useState({});
  const isXiaoCao = branchName.indexOf('小草科技') >= 0;

  useEffect(
    () => {
      // 房用户信息加载好后，再去设置当前tree组件的数据
      if (!isInfoReady) {
        setLoading(false);
        return;
      }
      const firstArea = {
        // 最顶层显示的层级
        name: branchName,
        id: companyId,
        level: branchLevel,
      };

      dispatch({
        type: 'accounts/zyGetCompaniesList',
        payload: {
          id: companyId, // 用户信息里面的所属区域id
        },
      })
        .then(() => {
          setLoading(false);
          // 初次加载设置好默认选中项（selectKey，setSelectedItem）
          setTreeData([firstArea]);
          setSelectKey([`${companyId}`]);
          setSelectedItem(firstArea);
        })
        .catch(() => {
          setLoading(false);
        });
    },
    [isInfoReady, branchLevel, branchName, companyId, dispatch],
  );

  useEffect(
    () => {
      // 通过监听selectedItem，设置对应的父级数据，用于添加账号时显示所属区域
      if (!isEmpty(selectedItem)) {
        const list_ = cloneDeep(treeList);
        dispatch({
          type: 'accounts/save',
          payload: {
            zySelectedArray: getParent(list_, selectedItem.id),
          },
        });
      }
    },
    [selectedItem, dispatch],
  );

  const onSelect = useCallback(
    // 点击公司时，请求对应的公司账号列表
    debounce(
      (selectedKeys, event) => {
        setSelectKey(selectedKeys);
        setSelectedItem(event.node.props.dataRef);
        selectedKeys[0] !== selectKey[0] &&
          dispatch({
            // 防止重复请求
            type: 'accounts/zyGetAcountsList',
            payload: {
              branch_id: event.node.props.dataRef.id,
              page: 1,
              pageSize: 20,
            },
          });
      },
      500,
      {
        leading: true,
        trailing: false,
      },
    ),
    [],
  );

  const onLoadData = treeNode =>
    new Promise(resolve => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      dispatch({
        type: 'accounts/zyGetCompaniesList',
        payload: {
          id: treeNode.props.dataRef.id,
        },
      }).then(res => {
        const { data } = res;
        treeNode.props.dataRef.children = [...isLegalData(data, [])];
        setTreeData([...treeList]);
        resolve();
      });
    });

  const updateZJTreeList = useCallback(
    id => {
      dispatch({
        type: 'accounts/zyGetCompaniesList',
        payload: {
          id,
        },
      }).then(res => {
        const { data } = res;
        const legalData = [...isLegalData(data, [])];
        setTreeData(prevTreeList => [...refreshData(prevTreeList, id, legalData)]);
      });
    },
    [dispatch, refreshData],
  );

  const refreshData = useCallback((data, id, newChild) => {
    data.forEach(val => {
      if (val.id == id) {
        val.children = newChild;
      } else if (val.children) {
        refreshData(val.children, id, newChild);
      }
    });
    return data;
  }, []);

  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.name} {...item} dataRef={item} />;
    });

  useImperativeHandle(
    ref,
    () => ({
      updateZJTreeList,
    }),
    [updateZJTreeList],
  );

  return (
    <div className={styles.select}>
      <Affix offsetTop={65}>
        <Spin spinning={loading}>
          {treeList.length == 0 &&
            !loading && (
              <Row type="flex" justify="center" className={styles.noData}>
                <Col>暂无数据</Col>
              </Row>
            )}
          {treeList.length !== 0 &&
            (branchLevel != 4 && key !== 'yjy') && (
              <Row type="flex" justify="end" align="middle" className={styles.add}>
                <Col>
                  <ZyAdd data={{ title: 'zj', companyId }} updateZJTreeList={updateZJTreeList}>
                    <a>
                      <Icon type="plus" />
                      {isXiaoCao ? '添加加盟商' : titleMap[key]}
                    </a>
                  </ZyAdd>
                </Col>
              </Row>
            )}
          <DirectoryTree
            className={branchLevel == 4 ? styles.pt10 : ''}
            showIcon={false}
            loadData={onLoadData}
            onSelect={onSelect}
            selectedKeys={selectKey}
          >
            {renderTreeNodes(treeList)}
          </DirectoryTree>
        </Spin>
      </Affix>
    </div>
  );
});

export default AddressTree;
